package com.tcredit.sdk.android;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * Created by xiong on 2017/8/15.
 */

public class httphelper {


    //校验json数据的
    public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");


    private final OkHttpClient okHttpClient;
    //尝试在联网的工具类里面就试着让更新界面执行在主线程
    Handler handler=new Handler();
    private FileOutputStream fos;
    private Context mContext;


    public  static httphelper create(Context context){

        httphelper helpter=new httphelper(context);
        return helpter;
    }


    private httphelper(Context context){
        this.mContext=context;
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(12, TimeUnit.SECONDS)
                .connectTimeout(12, TimeUnit.SECONDS).build();
//                .addInterceptor(new AddCookiesInterceptor())
//                .addInterceptor(new ReceivedCookiesInterceptor()).build();

    }


    public void doget(String url, final httpcallback h){
        Request request=new Request.Builder().get()
                .url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.fail(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final ResponseBody body = response.body();
                final String string = body.string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.success(string);
                    }
                });

            }
        });

    }


    //验证签名。
    public void dopost(String url, String newsign, final httpcallback h){
        final Request request=new Request.Builder().url(url).post(RequestBody.create(JSON,newsign)).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.fail(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                final String string = body.string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.success(string);
                    }
                });


            }
        });

    }



    private static String getMimeType(String filename) {
        FileNameMap filenameMap = URLConnection.getFileNameMap();
        String contentType = filenameMap.getContentTypeFor(filename);
        if (contentType == null) {
            contentType = "application/octet-stream"; //* exe,所有的可执行程序
        }
        return contentType;
    }



    public void UpdataParamsPost(String url, Map<String ,String> datas, final httpcallback h){
        RequestBody formBody=null;
        FormBody.Builder builder = new FormBody.Builder();
        // FormBody.Builder add=null;
        LogUtil.e("--接口的地址是--"+url);
        Iterator iter = datas.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String val =  (String)entry.getValue();
            formBody=builder.add(key,val).build();
        }
        Request request=new Request.Builder().url(url).post(formBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.fail(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                //待会测试下这个响应码2.5
                int code = response.code();
                LogUtil.e("---响应码是多少---"+code);
                final String string = body.string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        h.success(string);
                    }
                });
            }
        });

    }



   public  interface  httpcallback{
       void success(String s);
       void fail(Exception e);
   }


//   //请求里面添加sessionid然后保存下来，方便下次请求验证！
//    public class AddCookiesInterceptor implements Interceptor {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request.Builder builder = chain.request().newBuilder();
//            HashSet<String> preferences= SharepreferenceUtils.getHashsetdata(App.mContext, "cookie", new HashSet<String>());
//            for (String cookie : preferences) {
//                //后台cookie的开头就是叫cookie。。。
//                builder.addHeader("Cookie", cookie);
//                Log.e("OkHttp", "Adding Header: " + cookie);
//            }
//            return chain.proceed(builder.build());
//        }
//    }

//    //这里是接收cookie
//    public class ReceivedCookiesInterceptor implements Interceptor {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Response originalResponse = chain.proceed(chain.request());
//            if (!originalResponse.headers("Set-Cookie").isEmpty()) {
//                HashSet<String> cookies = new HashSet<>();
//                for (String header : originalResponse.headers("Set-Cookie")) {
//                    cookies.add(header);
//                    Log.e("---Received",cookies+"");
//                }
//                SharepreferenceUtils.saveHashsetdata(App.mContext,"cookie",cookies);
//            }
//            return originalResponse;
//        }
//    }

}
